<!--  -->
<template>
  <el-dialog v-model="dialogVisible" :title="ruleForm.id ? '编辑角色' : '新增角色'" width="600" :before-close="handleClose">
    <el-form class="form" ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item label="角色名" prop="name">
        <el-input v-model="ruleForm.name" />
        <!-- {{ ruleForm }} -->
      </el-form-item>
      <el-form-item label="权限" prop="menus">
        <!-- 树形选择 -->
        <div style="max-height:300px;overflow-y: auto;width:100%">
          <el-tree ref="treeRef" @check-change="handleChange" style="max-width: 600px" :data="menus" show-checkbox
            default-expand-all node-key="id" highlight-current :props="defaultProps" />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang='ts' setup>
import { Role } from '../../service/administratorrole/type';
import { getMenu, add } from '../../service/administratorrole/administratorrole';
import { reactive, defineEmits, ref, onMounted, defineProps } from 'vue'
import { FormInstance, FormRules,ElMessage } from 'element-plus'
const props = defineProps({
  editData: {
    type: Object
  }
})
//控制对话框的显示
const dialogVisible = ref(true)
const emit = defineEmits(["close"])
const treeRef = ref<any>();
//定义参数(添加/修改的数据)
const ruleForm = reactive<Role>({
  id: 0,
  name: '',
  menus: []
})
const ruleFormRef = ref<FormInstance>()
//表单校验
const rules = reactive<FormRules<Role>>({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  menus: [
    { required: true, message: '请选择权限', trigger: 'change' }
  ],
})
//关闭弹框
const handleClose = (done: () => void) => {
  console.log("000",done);
  emit("close");
}
//获取所有权限
const handleChange = () => {
  //获取当前选中的Key(id)
  var ids = treeRef.value.getCheckedKeys();
  //将选中的id赋值给ruleForm
  ruleForm.menus = ids.map((item: any) => ({ id: item }));
}
const submit = () => {
  ruleFormRef.value?.validate((valid: any) => {
    if (valid) {
      // 如果校验成功则进行添加数据
       postData();
      //关闭弹框
      
    }
  })
}
const postData = async () => {
  const res: any = await add(ruleForm);
  console.log(222, res);
  if (res.errCode === 10000) {
     ElMessage.success(ruleForm.id?"修改成功":"添加成功");
    emit("close",true);
  } else {
    ElMessage.error("添加失败");
  }
}
const defaultProps = { label: "name" };
const menus = ref([]);
// 获取所有权限列表
const getMenuData = async () => {
  const res: any = await getMenu(ruleForm.id);
  console.log(21312,ruleForm.id);
  
  console.log(21312,res.data.list);
  if (res.errCode === 10000) {
    menus.value = res.data.list;
    let ids: any = [];
    // 不建议使用 双重for循环  ，改成递归
    // menus.value.forEach((item: any) => {
    //   if (item.checked == 1) {
    //     ids.push(item.id);
    //   }
    //   item.children?.length && item.children.forEach((item2: any) => {
    //     if (item2.checked == 1) {
    //       ids.push(item2.id);
    //     }
    //   })
    // })
    collectCheckedIds(menus.value, ids);
    console.log(999, ids);
    //数据回显
    treeRef.value.setCheckedKeys(ids)
    ruleForm.menus=ids.map((item:any)=>({id:item}))
  }
  function collectCheckedIds(menus: any[], ids: number[]) {
      menus.forEach((item: any) => {
        if (item.checked == 1) {
          ids.push(item.id);
        }
        if (item.children?.length) {
          collectCheckedIds(item.children, ids); // 递归调用
        }
      });
    }
}
onMounted(() => {
  ruleForm.id = Number(props.editData!.id);
  ruleForm.name = props.editData!.name;
  getMenuData(); // 获取菜单数据
})
</script>
<style scoped>
.form {
  padding: 30px 50px;
}
</style>